package com.example.oj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.oj.entity.UserRegistration;
import com.example.oj.service.UserRegistrationService;
import com.example.oj.mapper.UserRegistrationMapper;
import com.example.ojcommon.common.ErrorCode;
import com.example.ojcommon.exception.BusinessException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @author 28651
 * @description 针对表【userRegistration】的数据库操作Service实现
 * @createDate 2024-03-22 11:31:10
 */
@Service
public class UserRegistrationServiceImpl extends ServiceImpl<UserRegistrationMapper, UserRegistration>
    implements UserRegistrationService {

  @Resource
  private UserRegistrationMapper userRegistrationMapper;

  @Override
  public Long getIsRegistry(Long userId, Long competitionId) {
    if (userId == null || competitionId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    QueryWrapper<UserRegistration> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("userId", userId);
    queryWrapper.eq("competitionId", competitionId);
    UserRegistration entity = userRegistrationMapper.selectOne(queryWrapper);
    if (entity == null) {
      return 0L;
    } else {
      return entity.getId();
    }
  }

  @Override
  public Integer updateUserRegistry(Long userId, Long competitionId, Integer isAdd) {
    if (userId == null || competitionId == null) {
      throw new BusinessException(ErrorCode.PARAMS_ERROR);
    }
    UserRegistration userRegistration = new UserRegistration();
    userRegistration.setUserId(userId);
    userRegistration.setCompetitionId(competitionId);
    if (isAdd == 1) {
      return userRegistrationMapper.insert(userRegistration);
    } else {
      Long id = this.getIsRegistry(userId, competitionId);
      return userRegistrationMapper.deleteById(id);
    }
  }
}




